-- https://github.com/akinsho/toggleterm.nvim

local utils = require("utils")
local helper = require("core.packages.toggleterm.helper")

local pack = {}

pack.lazy = {
    -- 使用动态路径查找toggleterm.nvim插件
    dir = (function()
        -- 获取根目录路径
        local home_dir = os.getenv("HOME") or os.getenv("USERPROFILE")
        if not home_dir then
            print("错误: 无法获取HOME环境变量")
            return ""
        end
        
        -- 规范化路径分隔符 - 使用正斜杠以兼容SH终端（基于BUSYBOX）
        local function normalize_path(path)
            return path:gsub("\\", "/")
        end
        
        -- 设置根目录
        local root_dir = normalize_path(home_dir)
        
        -- 从根目录构建toggleterm.nvim插件路径（直接从files开始）
        return utils.path.join(root_dir, "files", "self", "toggleterm.nvim")
    end)(),
    event = { "UIEnter" },
}

function pack.before_load()
    pack.plugin = require("toggleterm")
end

function pack.load()
    helper.load()

    pack.plugin.setup({
        start_in_insert = true,  -- 终端打开时直接进入插入模式
        shade_terminals = true,
        shading_factor = 1,
        on_open = helper.on_open,
        highlights = {
            Normal = {
                link = "Normal",
            },
            NormalFloat = {
                link = "NormalFloat",
            },
            FloatBorder = {
                link = "FloatBorder",
            },
        },
        -- 使用toggleterm.nvim插件内置的动态shell路径检测功能
        -- 插件会自动在Windows环境下检测有效的shell路径
    })
end

function pack.after_load() end

function pack.register_maps()
    utils.map.bulk_register({
        {
            mode = { "n" },
            lhs = "<leader>cr",
            rhs = "<cmd>CodeRunner<cr>",
            options = { silent = true },
            description = "Code running in terminal",
        },
        {
            mode = { "n" },
            lhs = "<leader>tf",
            rhs = helper.switch_float_term,
            options = { silent = true },
            description = "Toggle float terminal",
        },
        {
            mode = { "n" },
            lhs = "<leader>tn",
            rhs = helper.switch_bottom_term,
            options = { silent = true },
            description = "New Terminal",
        },
    })
end

return pack